import { ref } from "vue";

/**
 * @提示信息
 * @parms { show }  当前接口是否需要提示判断
 * @parms { title } 提示文字信息
 * @parms { icon }  提示图标  默认none没有
 */
export const Toast = (title: string, icon: any = 'none') => {
    return uni.showToast({
        title,
        icon,
    })
}
/**
 * @弹出框提示
 * @parms { content }     提示信息
 * @parms { confirmText } 确定按钮文字
 * @parms { navToshow }   跳转开关  默认false关闭  true打开
 */
export const Modal = (title: string = '提示', content: string = '', confirmText: string = '确定',) => {
    return new Promise((resolve, reject) => {
        uni.showModal({
            title,
            content,
            confirmText,
            showCancel: true,
            success: (res) => {
                // 确定
                if (res.confirm) {
                    resolve(res)
                }
                // 取消
                else if (res.cancel) {
                    reject(res)
                }
            }
        })
    })
}
/**
 * @跳转
 * @parms {url} 跳转链接
 */
export const NavTo = (url = '') => {
    return uni.navigateTo({
        url,
    })
}

/**
 * @跳转
 * @parms {url} 跳转链接
 */
export const Back = () => {
    return uni.navigateBack({
        delta: 1
    })
}
/**
 * @底部栏跳转
 * @parms {url} 跳转链接
 */
export const SwcTo = (url: string) => {
    return uni.switchTab({
        url,
    })
}

export const RediTo = (url: string) => {
    return uni.redirectTo({
        url,
    })
}
/**
 * @设置页面标题
 * @parms { title } 标题
 */

export const setTitle = (title: string) => {
    uni.setNavigationBarTitle({
        title,
    })

}

/**
 * 时间戳转换
 * @param { date } 时间戳
 */
export const forDate = (date: number) => {
    if (date) {
        const time = new Date(date * 1000)
        const M = time.getMonth() + 1
        const D = time.getDate()
        const h = time.getHours()
        const m = time.getMinutes()
        return `${M}-${D} ${h}:${m}`
    }
    return ''
}


/**
 * @时间戳转换
 * @param { date } 时间戳
 */
export const forDate_day = (date: number) => {
    const h = parseInt(String(date / 60 / 60))
    let m: string | number = parseInt(String(date / 60 % 60))
    const s = parseInt(String(date % 60))

    m = m < 10 ? '0' + m : m
    return `${h}:${m}:${s}`
}

/**
 * @获取当前定位
 */
export const getLocation = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: 'wgs84',
            isHighAccuracy: true,
            altitude: true,
            // timeout: 3,
            // geocode: true,
            success: (res) => {
                // console.log(res, 'getLocation地理位置')
                resolve(res)
            },
            fail: (error) => {
                console.log(error)
                reject(error)
            }
        })
    })

}


/**
 *
 * @获取实时定位
 */

export const onLocationChange = () => {
    return new Promise((resolve, reject) => {
        uni.onLocationChange((res: any) => {
            resolve(res)
        })

    })
}

//进行经纬度转换为距离的计算
function Rad(d: number) {
    return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
// const GetDistance = async (lat1, lng1,lat2,lng2) => {
export const GetDistance = (lat1: number, lng1: number, lat2: number, lng2: number) => {
    //console.log(lat1, lng1, '自己的位置');
    //console.log(lat2, lng2);
    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里
    let ss = s.toFixed(2);
    //console.log(s, '公里');
    //console.log(ss, '公里');
    return ss;
}

// #ifdef APP-PLUS
/**
 * 语音播报
 */
const bgAudioManager = uni.getBackgroundAudioManager();
const playMode = ref(0) //播放声道（扬声器 0，听筒 1）
const playState = ref(0)//play回调中播放参数
const playState2 = ref(0)//play回调中播放参数
const playState3 = ref(0)//play回调中播放参数
const voicePlayer: any = ref(null)
const voicePlayer2: any = ref(null)
const voicePlayer3: any = ref(null)
export const initVoice = () => {
    voicePlayer.value = plus.audio.createPlayer("/static/notice.mp3");
    voicePlayer2.value = plus.audio.createPlayer("/static/td.mp3");
	voicePlayer3.value = plus.audio.createPlayer("/static/newinfo.mp3");
    voicePlayer.value.setRoute(playMode.value);
    voicePlayer2.value.setRoute(playMode.value);
	voicePlayer3.value.setRoute(playMode.value);

    // 监听自然播放完成
    voicePlayer.value.addEventListener('ended', () => {
        //console.log('播放完毕了');
    });

    // 监听音频可以开始播放事件
    voicePlayer.value.addEventListener('play', () => {
        // 首次播放时会执行两次回调
        if (playState.value !== 2) {
            // plus.audio.ROUTE_SPEAKER：扬声器 0
            // plus.audio.ROUTE_EARPIECE：听筒 1
            voicePlayer.value.setRoute(playMode.value);
            playState.value++;
        }
        //console.log('play==========playState.value=' + playState.value);
    });

    // 监听音频播放错误事件
    voicePlayer.value.addEventListener('error', (err: any) => {
        console.log('报错err', err);
    });

    // 监听自然播放完成
    voicePlayer2.value.addEventListener('ended', () => {
        console.log('播放完毕了');
    });

    // 监听音频可以开始播放事件
    voicePlayer2.value.addEventListener('play', () => {
        // 首次播放时会执行两次回调
        if (playState2.value !== 2) {
            // plus.audio.ROUTE_SPEAKER：扬声器 0
            // plus.audio.ROUTE_EARPIECE：听筒 1
            voicePlayer2.value.setRoute(playMode.value);
            playState2.value++;
        }
        console.log('play==========playState2.value=' + playState2.value);
    });

    // 监听音频播放错误事件
    voicePlayer2.value.addEventListener('error', (err: any) => {
        console.log('报错err', err);
    });
	
	// 监听自然播放完成
	voicePlayer3.value.addEventListener('ended', () => {
	    //console.log('播放完毕了');
	});
	
	// 监听音频可以开始播放事件
	voicePlayer3.value.addEventListener('play', () => {
	    // 首次播放时会执行两次回调
	    if (playState3.value !== 2) {
	        // plus.audio.ROUTE_SPEAKER：扬声器 0
	        // plus.audio.ROUTE_EARPIECE：听筒 1
	        voicePlayer3.value.setRoute(playMode.value);
	        playState3.value++;
	    }
	    //console.log('play==========playState.value=' + playState.value);
	});
	
	// 监听音频播放错误事件
	voicePlayer3.value.addEventListener('error', (err: any) => {
	    console.log('报错err', err);
	});
}

export const soundPlay = async (type: number) => {
    // #ifdef APP-PLUS
    // await play()
    console.log('新订单');

    type == 1 ? await playVoice() :   type == 9?await playVoice3(): await playVoice2();
    // #endif
}

//播放音频方法一
export const playVoice = async () => {
    for (var i = 1; i < 4; i++) {
        ((i) => {
            setTimeout(async () => {
                await voicePlayer.value.play();
                //console.log("play times =" + i)
            }, (i) * 2500);
        })(i);
    }
}

//播放音频方法一
export const playVoice2 = async () => {
    for (var i = 1; i < 4; i++) {
        ((i) => {
            setTimeout(async () => {
                await voicePlayer2.value.play();
                console.log("play2 times =" + i)
            }, (i) * 2500);
        })(i);
    }
}
//播放音频方法一
export const playVoice3 = async () => {
    for (var i = 1; i < 4; i++) {
        ((i) => {
            setTimeout(async () => {
                await voicePlayer3.value.play();
            
            }, (i) * 2500);
        })(i);
    }
}

//播放音频方法二
export const play = async () => {
    bgAudioManager.title = '外卖狮';
    bgAudioManager.singer = '暂无';
    bgAudioManager.coverImgUrl = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/music-a.png';
    bgAudioManager.src = '../../static/notice.mp3';

    for (var i = 1; i < 5; i++) {
        ((i) => {
            setTimeout(() => {
                //开始播放
                bgAudioManager.play()
                //播放完成的回调
                bgAudioManager.onEnded(() => {
                    //停止播放
                    bgAudioManager.stop()
                })
                console.log("play times =" + i)
            }, (i) * 1200);
        })(i);
    }
}

// #endif


/**
 * gps 工具类
 */
export const GPS = {
    PI: 3.14159265358979324,
    x_pi: 3.14159265358979324 * 3000.0 / 180.0,
    delta: function (lat: number, lon: number) {
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
        var dLat = this.transformLat(lon - 105.0, lat - 35.0);
        var dLon = this.transformLon(lon - 105.0, lat - 35.0);
        var radLat = lat / 180.0 * this.PI;
        var magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        var sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
        return { 'lat': dLat, 'lon': dLon };
    },

    //WGS-84 to GCJ-02
    gcj_encrypt: function (wgsLat: number, wgsLon: number) {
        if (this.outOfChina(wgsLat, wgsLon))
            return { 'lat': wgsLat, 'lon': wgsLon };

        var d = this.delta(wgsLat, wgsLon);
        return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
    },

    // two point's distance
    distance: function (latA: number, lonA: number, latB: number, lonB: number) {
        var earthR = 6371000.;
        var x = Math.cos(latA * this.PI / 180.) * Math.cos(latB * this.PI / 180.) * Math.cos((lonA - lonB) * this.PI / 180);
        var y = Math.sin(latA * this.PI / 180.) * Math.sin(latB * this.PI / 180.);
        var s = x + y;
        if (s > 1) s = 1;
        if (s < -1) s = -1;
        var alpha = Math.acos(s);
        var distance = alpha * earthR;
        return distance;
    },
    outOfChina: function (lat: number, lon: number) {
        if (lon < 72.004 || lon > 137.8347)
            return true;
        if (lat < 0.8293 || lat > 55.8271)
            return true;
        return false;
    },
    transformLat: function (x: number, y: number) {
        var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    },
    transformLon: function (x: number, y: number) {
        var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
        return ret;
    }
};

// app跳转到应用设置页面
export const setUp = () => {
    // #ifdef APP-PLUS
    if (plus.os.name == 'Android') {
        var Intent = plus.android.importClass("android.content.Intent");
        var Settings = plus.android.importClass("android.provider.Settings");
        var Uri = plus.android.importClass("android.net.Uri");
        var mainActivity = plus.android.runtimeMainActivity();
        var intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    } else {
        var UIApplication = plus.ios.import("UIApplication");
        var application2 = UIApplication.sharedApplication();
        var NSURL2 = plus.ios.import("NSURL");
        // var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
        var setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);

        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    }
    // #endif
}

// 判断手机是否开启了相机权限 0:未授权 1:允许 -1:明确拒绝 
export const getToPhone = () => {
    return new Promise(resolve => {
        if (plus.os.name == 'Android') {
            plus.android.requestPermissions(
                ['android.permission.ANSWER_PHONE_CALLS', //手动 挂断和接听 需要这个权限
                    "android.permission.MODIFY_AUDIO_SETTINGS", //手动 挂断和接听 需要这个权限
                    "android.permission.CALL_PHONE", //手动 挂断和接听 需要这个权限
                    "android.permission.READ_PHONE_STATE", //>监听电话状态 需要这个权限
                    "android.permission.READ_CALL_LOG", //获取号码需要这个权限
                    "android.permission.READ_AUDIO" // 录音权限
                ],
                function (resultObj) {
                    for (var i = 0; i < resultObj.granted.length; i++) {
                        var grantedPermission = resultObj.granted[i];
                        console.log('已获取的权限：' + grantedPermission);
                        resolve(1)
                    }
                    for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                        var deniedPresentPermission = resultObj.deniedPresent[i];
                        console.log('拒绝本次申请的权限：' + deniedPresentPermission);
                        resolve(0)
                    }
                    for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                        var deniedAlwaysPermission = resultObj.deniedAlways[i];
                        console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
                        resolve(-1)
                    }
                },
                function (error) {
                    console.log('申请权限错误：' + error.code + " = " + error.message);
                });
        } else {
            resolve(1)
        }
    })
}

